<?php
namespace App\Services\System;

use App\Common\Utils\Helper;
use App\Models\Participant;
use App\Models\System\User;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Models\Files;

class FilesService
{

    public function __construct()
    {
        $this->activityCategory = [
            'TEARRESEARCH_OPEN_TABLE' => '公开教学',
            'EW_EXCHANGE_EXPERIENCE_TABLE' => '经验交流',
            'TEACHING_PROJECT_TABLE' => '项目化',
            'TEACHING_TEACHER_TABLE' => '全员导师制',
            //'EW_SUBJECT_RESEARCH_TABLE' => '课题研究',
            'EW_PAPER_PUBLISH_TABLE' => '文章发表',
            'EW_PAPER_PUBLISH_TABLE2' => '论著发表',
            'TEARRESEARCH_DEVELOP_SUBJECT_TABLE' => '开发科目',
            'TEACHERTRAINING_ACTIVITY_TABLE' => '教研活动',
            //'EW_EDU_PLAN_TABLE' => '计划和总结',
            'TEACHER_HONOR_TABLE' => '班级荣誉',
            //'EW_THEME_ACTIVITY_TABLE' => '班级主题活动',
            'TEACHER_AWARD_TABLE' => '获奖情况',
            'IMPORTANTWORK_TEACHING_SITUATION_TABLE' => '带教情况',
            'IMPORTANTWORK_IN_SCHOOL_TABLE' => '校内工作',
            'IMPORTANTWORK_OUT_SCHOOL_TABLE' => '校外工作',
            'TEACHERTRAINING_OUTTRAINING_TABLE' => '外出培训',
            'TEACHERTRAINING_OTHER_TABLE' => '其他培训',
            'TEACHERTRAINING_JOINTRAINING_TABLE' => '参与教研',
            'TEACHING_REFLECT_TABLE' => '教学反思（案例）',
        ];
    }

    /**
     * 获取列表
     * @author qiankun
     * @datetime 2025-03-19
     */
    public function getFilesList($request)
    {
        $limit = $request['limit'] ?? 10;
        $where = [];
        $jsonSearch = [];
        if (isset($request['search']['data_version_id'] )&& !empty($request['search']['data_version_id'])){
            $where[] = ['a.data_version_id','=',$request['search']['data_version_id']];
        }
        if (isset($request['search']['name']) && !empty($request['search']['name'])){
            $keyword = Helper::check_param($request['search']['name']);
            $where[] = [DB::raw("(files.name like '%{$keyword}%')"),'1'];
        }
        if (isset($request['search']['activity_category'] )&& !empty($request['search']['activity_category'])){
            if(in_array($request['search']['activity_category'],['EW_PAPER_PUBLISH_TABLE2','EW_PAPER_PUBLISH_TABLE'])){
                $where[] = ['a.activity_category', '=', 'EW_PAPER_PUBLISH_TABLE'];
                if($request['search']['activity_category'] == 'EW_PAPER_PUBLISH_TABLE') {
                    $jsonSearch['pubications_publish_type'] = 128;//文章发表
                }else{
                    $jsonSearch['pubications_publish_type'] = 129;//论著发表
                }
            }else if($request['search']['activity_category'] == 'EW_EXCHANGE_EXPERIENCE_TABLE' ){
                $where[] = [DB::raw("( a.activity_category in ('EW_EXCHANGE_EXPERIENCE_TABLE', 'TEARRESEARCH_EXCHANGE_TABLE'))"),'1'];
            }else if($request['search']['activity_category'] == 'TEARRESEARCH_OPEN_TABLE' ) {
                $where[] = [DB::raw("( a.activity_category in ('TEARRESEARCH_OPEN_TABLE', 'EW_CLASS_MEETING_TABLE'))"),'1'];
            }else {
                $where[] = ['a.activity_category', '=', $request['search']['activity_category']];
            }
        }
        if (isset($request['search']['grade'] )&& !empty($request['search']['grade'])){
            $jsonSearch['grade'] = $request['search']['grade'];
        }
        if (isset($request['search']['course'] )&& !empty($request['search']['course'])){
            $jsonSearch['course'] = $request['search']['course'];
        }
        if (isset($request['search']['category'] )&& !empty($request['search']['category'])){
            $jsonSearch['category'] = $request['search']['category'];
        }

        /**
        if (isset($request['search']['class_item'] )&& !empty($request['search']['class_item'])){
            $jsonSearch['class_item'] = $request['search']['class_item'];
        }**/
        $where[] = ['files.is_push','=',1];
        //DB::connection()->enableQueryLog();
        $result = Files::where($where)->select('files.*', 'a.activity_category','a.pubications_publish_type','a.level','a.category','a.creator_id')
                ->leftJoin('activity_info as a' ,'a.id','=','files.ilk_id')
                ->with('creator')
                ->when(!empty($jsonSearch), function($q) use($jsonSearch) {
                    foreach($jsonSearch as $k => $id) {
                        $q->whereRaw(" JSON_EXTRACT(a.`".$k."`,'$[0].optionId') = $id");
                    }
                })
                ->orderBy('created_at','desc')
                ->paginate($limit)
                ->toArray();
        //dd(DB::getQueryLog());
        foreach ($result['data'] as &$item){
            $item['category_name'] = $item['activity_category_name'] = $item['level_name'] = '';
            if($item['ilk_type'] == 1) {
                if ($item['activity_category'] == 'EW_PAPER_PUBLISH_TABLE' || $item['activity_category'] == 'TEARRESEARCH_PUBLISH_TABLE') {
                    if ($item['pubications_publish_type']) {
                        $typeData = json_decode($item['pubications_publish_type'], 1);
                        if ($typeData[0]['optionId'] == 128) {
                            $item['activity_category_name'] = '文章发表';
                        } else {
                            $item['activity_category_name'] = '论著发表';
                        }
                    }
                }else if($item['activity_category'] == 'TEARRESEARCH_EXCHANGE_TABLE'){
                    $item['activity_category_name'] = '经验交流';
                }else if(in_array($item['activity_category'] ,['TEARRESEARCH_OPEN_TABLE','EW_CLASS_MEETING_TABLE'] )){
                    $item['activity_category_name'] = '公开教学';
                }else {
                    $item['activity_category_name'] = $this->activityCategory[$item['activity_category']] ?? '';
                }
            }else if($item['ilk_type'] == 2){
                $item['activity_category_name'] = '教研活动';
            }else{
                $item['activity_category_name'] = '-';
            }
            $item['nickname'] = $item['creator']['nickname'] ?? '';//名称
            if(!empty($item['category'])){
                $categoryData = json_decode($item['category'], 1);
                $item['category_name'] = $categoryData[0]['selectValue'] ?? '';
            }
            if(!empty($item['level'])){
                $levelData = json_decode($item['level'], 1);
                $item['level_name'] = $levelData[0]['selectValue'] ?? '';
            }
        }
        $result['limit'] = $limit;
        $result['from'] = $this->activityCategory;
        return $result;
    }

}
